<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px"
			class="queryForms">
			<el-form-item label="申请日期" prop="applyTime">
				<el-date-picker v-model="queryParams.applyTime" type="date" value-format="yyyy-MM-dd"
					placeholder="请选择接收日期" />
			</el-form-item>
			<el-form-item label="编号" prop="number">
				<el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter.native="handleQuery"
					maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="申请人" prop="createBy">
				<el-input v-model="queryParams.createBy" placeholder="请输入申请人" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="审批状态" prop="approvalStatus">
				<el-select v-model="queryParams.approvalStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.default_approve" :key="dict.value" :label="dict.label"
						:value="dict.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['equipApply:applylist:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
					v-hasPermi="['equipApply:applylist:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-circle-check" size="mini" @click="handleSubmits"
					v-hasPermi="['equipApply:applylist:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-s-order" size="mini" @click="handleApprove"
					v-hasPermi="['equipApply:applylist:approve']">审批</el-button>
			</el-col>

			<CreateForm :ids="ids" formtype="t_appliLists" />
			<right-toolbar @changeTableData="changeTableData" menuNames="applylist7" :showSearch.sync="showSearch"
				@queryTable="getList" :columns.sync="columns" perm="equipApply:applylist:list"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="auxiliaryConsumablesTypeList"
				@selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" />
				<el-table-column label="编号" prop="number" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="器材申请单编号" prop="recordNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="申请日期" prop="applyTime" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[2].visible" />
				<el-table-column label="要求完成日期" prop="completeTime" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="审批状态" align="center" prop="approvalStatus" width="150"
					:show-overflow-tooltip="true" v-if="columns[4].visible">
					<template slot-scope="scope">
						<!-- <div @click="showApproveList(scope.row)">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</div> -->
						<el-tag type="info" v-if="scope.row.approvalStatus === '0'" class="disableClick">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag v-if="scope.row.approvalStatus === '1'" @click="showApproveList(scope.row)"
							class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag type="success" v-if="scope.row.approvalStatus === '2'"
							@click="showApproveList(scope.row)" class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag type="danger" v-if="scope.row.approvalStatus === '3'"
							@click="showApproveList(scope.row)" class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="申请人" prop="createBy" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right"
					width="180">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-tickets" @click="handleJump(scope.row)"
							v-hasPermi="['equipApply:applylist:lists']">列表</el-button>
						<el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleSubmit(scope.row)"
							v-show="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
							v-hasPermi="['equipApply:applylist:submit']">提交</el-button>
						<!-- 审批中显示 -->
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleApprove(scope.row)"
							v-show="scope.row.approvalStatus == '1' && scope.row.userApprovalStatus == '0'"
							v-hasPermi="['equipApply:applylist:approve']">审批</el-button>
						<!-- 更多 -->
						<el-dropdown size="mini" @command="command => handleCommand(command, scope.row)"
							v-hasPermi="['equipApply:applylist:edit', 'equipApply:applylist:remove', 'equipApply:applylist:annex']">
							<el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item
									v-show="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
									command="handleUpdate"
									v-hasPermi="['equipApply:applylist:edit']">修改</el-dropdown-item>
								<el-dropdown-item
									v-show="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
									command="handleDelete"
									v-hasPermi="['equipApply:applylist:remove']">删除</el-dropdown-item>
								<el-dropdown-item command="handleJump2"
									v-hasPermi="['equipApply:applylist:annex']">附件</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination9" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改器材申请单对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form2" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="编号" prop="number">
					<el-input v-model="form.number" placeholder="请输入编号" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="申请单编号" prop="recordNumber">
					<el-input v-model="form.recordNumber" placeholder="请输入申请单编号" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="申请日期" prop="applyTime">
					<el-date-picker v-model="form.applyTime" type="date" value-format="yyyy-MM-dd"
						placeholder="请选择接收日期" />
				</el-form-item>
				<el-form-item label="要求完成日期" prop="completeTime">
					<el-date-picker v-model="form.completeTime" type="date" value-format="yyyy-MM-dd"
						placeholder="请选择要求完成日期" />
				</el-form-item>
				<div class="add-form-table">
					<el-table :data="addtablelist">
						<el-table-column label="器材名称" prop="deviceName" align="center" min-width="150">
							<template slot-scope="scope">
								<el-input v-model="scope.row.deviceName" placeholder="请输入/20" size="small"
									maxlength="20"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="技术要求" prop="demand" align="center" min-width="150">
							<template slot-scope="scope">
								<el-input v-model="scope.row.demand" placeholder="请输入/20" size="small"
									maxlength="20"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="件号" prop="partNumber" align="center" min-width="150">
							<template slot-scope="scope">
								<el-input v-model="scope.row.partNumber" placeholder="请输入/20" size="small"
									maxlength="20"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="数量" prop="num" align="center" min-width="150">
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.num" placeholder="请输入" size="small" :min="0"
									:max="99999999" :precision="0" :controls="false"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="用途" prop="purpose" align="center" min-width="150">
							<template slot-scope="scope">
								<el-input v-model="scope.row.purpose" placeholder="请输入/100" size="small"
									maxlength="100"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="操作" prop="name" min-width="100" align="center"
							:show-overflow-tooltip="true">
							<template slot-scope="scope">
								<el-button v-if="scope.$index == 0" type="text" @click="addOne()">添加</el-button>
								<el-button v-else type="text" @click="delOne(scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
	</div>
</template>

<script>
import { listApply, getApply, delApply, addApply, updateApply, submitQuality, qualityApprove } from "@/api/equipApply/applylist"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { mapGetters } from "vuex"
import CreateForm from "@/views/components/CreateForm"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'      
import { getcolumn } from "@/api/selectList"
export default {
	name: "Applylist",
	dicts: ["default_approve"],
	mixins: [searchStateMixin],      
	components: { ApproveTemplete, RecordsTemplete, CreateForm },
	data() {
		return {
			eleTabTop: 0, //表格容器距浏览器顶部距离
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 器材申请单表格数据
			auxiliaryConsumablesTypeList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				number: undefined,
				createBy: undefined,
				applyTime: undefined,
				approvalStatus: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				number: [{ required: true, message: "请输入编号", trigger: "blur" }],
				applyTime: [{ required: true, message: "请选择申请日期", trigger: "blur" }],
				recordNumber: [{ required: true, message: "请输入申请单编号", trigger: "blur" }],
				completeTime: [{ required: true, message: "请选择要求完成日期", trigger: "blur" }]
			},
			addtablelist: [{}],
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			openRecords: false,
			approveRecord: [],
			// 列信息
			columns: [
				{ key: 0, label: `编号`, visible: true },
				{ key: 1, label: `器材申请单编号`, visible: true },
				{ key: 2, label: `申请日期`, visible: true },
				{ key: 3, label: `要求完成日期`, visible: true },
				{ key: 4, label: `审批状态`, visible: true },
				{ key: 5, label: `申请人`, visible: true }
			]
		}
	},
	computed: {
		...mapGetters(["sidebar"])
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData && Object.keys(newQuery.queryData).length != 0) {
					this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
					// this.getSize()
				}  this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},

	created() {
			// this.getSize()
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			// 清除URL中的查询参数（不刷新页面）
			this.resetForm("queryForm")
			window.history.replaceState({}, document.title, window.location.pathname)
		}
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination9" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询器材申请单列表 */
		getList() {
			this.loading = true
			listApply(this.queryParams).then(response => {
				this.auxiliaryConsumablesTypeList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 更多操作触发
		handleCommand(command, row) {
			this[command](row)
			// switch (command) {
			// 	case "handleUpdate":
			// 		this.handleUpdate(row)
			// 		break
			// 	case "handleDelete":
			// 		this.handleDelete(row)
			// 		break
			// 	case "handleJump2":
			// 		this.handleJump2(row)
			// 		break
			// 	default:
			// 		break
			// }
		},

		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				number: undefined,
				recordNumber: undefined,
				applyTime: undefined,
				completeTime: undefined
			}
			this.addtablelist = [{}]
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()    
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams.approvalStatus = undefined
			this.queryParams.number = undefined
			this.clearSearchCache()              
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = "添加器材申请单"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getApply(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改器材申请单"
				this.addtablelist = response.data.tequipmentRequestDeviceList
			})
		},
		// 添加一行
		addOne() {
			let list = this.addtablelist
			if (!list[list.length - 1].deviceName) {
				this.$modal.msgError("请输入器材信息")
				return false
			}
			this.addtablelist.push({})
		},
		// 删除一行
		delOne(index) {
			this.addtablelist.splice(index, 1)
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					let list = this.addtablelist
					if (!list[list.length - 1].deviceName) {
						this.$modal.msgError("请输入器材信息")
						return false
					}
					// 判断数量
					let checknum = list.find(item => {
						return !item.num || item.num <= 0
					})
					if (checknum) {
						if (checknum.num == 0) {
							this.$modal.msgError("器材数量不能为0")
						} else {
							this.$modal.msgError("请输入器材数量")
						}
						return false
					}
					this.form.tequipmentRequestDeviceList = this.addtablelist
					if (this.form.id != undefined) {
						updateApply(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.getList()
						})
					} else {
						addApply(this.form).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.getList()
						})
					}
				}
			})
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "9"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delApply(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		// 提交
		handleSubmits(row) {
			const _this = this
			this.$modal
				.confirm(`是否确认提交数据项？`)
				.then(function () {
					return submitQuality({
						workIds: _this.ids,
						workflowType: "9"
					})
				})
				.then(() => {
					_this.getList()
					localStorage.setItem("todoMessage", "apply1")
					_this.$modal.msgSuccess("提交成功")
					_this.$refs.table.clearSelection()
				})
				.catch(() => { })
		},
		// 提交
		handleSubmit(row) {
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: row.id,
						workflowType: "9",
						// 1是提交，3是重复提交
						submitStatus: row.approvalStatus == "0" ? "1" : "2"
					}
					return submitQuality(data)
				})
				.then(() => {
					this.getList()
					localStorage.setItem("todoMessage", "apply2")
					this.$modal.msgSuccess("操作成功")
				})
				.catch(err => {
					console.log(err)
				})
		},

		// 审批
		handleApprove(row) {
			if (row.id) {
				this.approveRow = {
					id: row.id,
					repairId: row.repairId
				}
			} else {
				this.approveRow = {}
			}
			this.openApprove = true
		},
		// 审批取消
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}
			let data = {
				approvalStatus: ret.approvalStatus,
				causeRejection: ret.causeRejection,
				workflowType: "9"
			}
			this.approveRow.id ? (data.id = this.approveRow.id) : (data.ids = this.ids)
			let res = await qualityApprove(data)
			if (res.code == 200) {
				this.$modal.msgSuccess("操作成功")
				this.getList()
				localStorage.setItem("todoMessage", "apply7")
				this.$refs.table.clearSelection()
			}
			this.openApprove = false
		},
		// 跳转到器材列表
		handleJump(row) {
			let url = "/equipApply/applyPlist?id=" + row.id
			this.$router.push(url)
		},
		// 跳转附件
		handleJump2(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 25,
					perm: "equipApply:applylist:annex"
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.add-form-table {
	width: 100%;

	::v-deep .el-input--small .el-input__inner {
		padding-right: 15px !important;
	}

	::v-deep .el-input-number--small .el-input__inner {
		text-align: left;
	}
}

::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 180px !important;
}
</style>
